package client;

//import java.io.BufferedReader;
import forumGUI.ConnectScreen;
import java.io.IOException;
//import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import messaage.ConnectMsg;
import messaage.Message;
import server.comm.Encoder;
import server.comm.SimpleEncoder;

public class TcpClient {
	//private MessageBuilder mb;
	private Runnable listener;
	private OutputStreamWriter osw;
	boolean _shouldClose;
	String sessionID;


	public TcpClient() {
		super();
		//mb = new MessageBuilder();
		this._shouldClose = false;
	}

	public void run(String serverName, int port,  ConnectScreen cs) {
		try {
			// create a socket and associate a UTF8 OutputStreamWriter to it
			Encoder encoder = new SimpleEncoder();
			InetAddress address = InetAddress.getByName(serverName);
			Socket socket = new Socket(address, port);
			this.listener = new ForumClientListener(socket);
                          ForumClientListener tempClient = (ForumClientListener)this.getListener();
                         tempClient.getConnector().addListener(cs);
			Thread listenerThread = new Thread(listener);
			listenerThread.start();
			this.osw = new OutputStreamWriter(socket
					.getOutputStream(), encoder.getCharset());
			//send connect message to server
			ConnectMsg conn = new ConnectMsg();
			System.out.println(conn.toString());
			osw.write(conn.toString());
			osw.flush();
			
		} catch (UnknownHostException e) {
			System.out.println("Unknown host. couldn't connect.");
			return;
		} catch (IOException e) {
			System.out.println("Error connecting, check host and port.");
			return;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * This method is used by the GUI in oreder to send the received messages through the socket.
	 * @param m: the message to send.
	 */
	public void sendMessage(Message m){
		System.out.println("in");
		//System.out.println(m.toString());
		if (m != null) {
			try {
				this.osw.write(m.toString());
				this.osw.flush();
			} catch (IOException e) {
				System.err.println("Error connecting, check host and port.");
			}
			System.out.print("> ");
		} else {
			System.out.println("Unknown command");
			System.out.print("> ");
		}
	}

	public Runnable getListener() {
		return this.listener;
	}
	
	
}
